package tj.eskhata.pos.dao.hibernate;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;

import tj.eskhata.pos.dao.GenericDao;

public class GenericDaoImpl implements GenericDao {

  private SessionFactory sessionFactory;

  public GenericDaoImpl() {
  }

  public SessionFactory getSessionFactory() {
    return sessionFactory;
  }

  public void setSessionFactory(SessionFactory sf) {
    this.sessionFactory = sf;
  }

  @SuppressWarnings("unchecked")
  public <T> T load(Class<T> type, long id) {
    return (T) getCurrentSession().get(type, id);
  }
  
  @SuppressWarnings("unchecked")
  public <T> List<T> findByCriteria(Class<T> type,Criterion... criterion) {
      Criteria crit = getCurrentSession().createCriteria(type);
      for (Criterion c : criterion) {
          crit.add(c);
      }
      return crit.list();
 }
    
  public Session getCurrentSession() {
    // presumes a current session, which we have through the
    // OpenSessionInViewFilter; doesn't work without that
    return sessionFactory.getCurrentSession();
  }
}
